import Editor from "../editor";
import isHotkey from "is-hotkey";
import { event as eventBus } from "../utils";

export class myKeyboardEvent {
  private _editor: Editor;
  private _container: HTMLElement;

  constructor (editor: Editor, container: HTMLElement) {
    this._editor = editor;
    this._container = container;
  }

  _beforeInputHandler(event: InputEvent) {
    event.preventDefault();

    const inputType = event.inputType;
    console.log(inputType)

    if (event.inputType === 'insertCompositionText') return;

    // 插入字符
    if (inputType === 'insertText') {
      const text = event.data;
      if (text) {
        this._editor.insertTextAtCursor(text);
      }
    }
    
    // 删除
    if (inputType === 'deleteContentBackward') {
      this._editor.removeTextAtCursor();
    } 
    
    // 换行
    if (inputType === 'insertParagraph') {
      this._editor.insertTextAtCursor('\n');
    } 
    
    // 黏贴（未处理换行）
    if (inputType === 'insertFromPaste') {
      const data = event.dataTransfer?.getData('text/plain');
      if (data) {
        this._editor.insertTextAtCursor(data);
      }
    }
  }

  _keydownHandler(event: KeyboardEvent) {
    // 撤销
    if (isHotkey('mod+z')(event)) {
      event.preventDefault()
      this._editor.undo && this._editor.undo();
    }
    
    // 回退
    if (isHotkey('mod+y')(event)) {
      event.preventDefault()
      this._editor.redo && this._editor.redo();
    }
  }

  _compositionstartHandler(event: CompositionEvent) {
    eventBus.emit('set_composing', true);
  }

  _compositionendHandler(event: CompositionEvent) {
    eventBus.emit('set_composing', false);
    this._editor.insertTextAtCursor(event.data);
  }

  addListeners () : void {
    this._container.addEventListener('beforeinput', this._beforeInputHandler.bind(this));
    this._container.addEventListener('keydown', this._keydownHandler.bind(this));
    this._container.addEventListener('compositionstart', this._compositionstartHandler.bind(this));
    this._container.addEventListener('compositionend',this._compositionendHandler.bind(this));
  }
}

export default KeyboardEvent;